package instantHelper.Raceway;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import instantHelper.ClosedMode.*;
import instantHelper.Models.CustomHttpClient;
import instantHelper.NormalMode.MyLocationListener;
import instantHelper.NormalMode.NormalModeAudioRecorder;
import instantHelper.NormalMode.NormalModePictureCapture;
import instantHelper.NormalMode.NormalModeVideoCapture;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.*;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class main extends Activity {

	private static final String TAG = main.class.getSimpleName();
	DbHelper myDBHelper;
	Button buttonHelp;
	private boolean isSettingAdd = false;
	private boolean isContactAdd = false;
	private String requestId;
	private String androidId;
	private String IMEI;
	private DbHelper myDbHelper;
	private String parentPath = InstantHelperConstant.PARENTFILENAME;
	LocationManager mlocManager;
	instantHelper.NormalMode.MyLocationListener mlocListener;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		androidId = SettingsUtil.getAndroidID(getApplicationContext());
		IMEI = SettingsUtil.getIMEIAddress(getApplicationContext());
		buttonHelp = (Button) findViewById(R.id.btnHelp);

		createParentPath(parentPath);
		helpButtonAvailable();

	}

	public void gpsAvailableControl() {
		LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (!locManager
				.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(
					"Your GPS is disabled! Would you like to enable it?")
					.setCancelable(false)
					.setPositiveButton("Enable GPS",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									showGpsOptions();
								}
							});
			builder.setNegativeButton("Do nothing, app will close",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
							finish();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
		}
	}

	void showGpsOptions() {
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(gpsOptionsIntent);
	}

	private void createParentPath(String parentPath2) {
		String filePath = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + parentPath2;
		File directory = new File(filePath);
		if (!directory.exists() && !directory.mkdirs()) {
			try {
				throw new IOException("Path to file could not be created.");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void onClickBtnClickHelp(View button) {

		Intent modeIntent = new Intent();
		requestId = sendHelpRequestToCentrallApp();
		modeIntent.putExtra("requestId", requestId);
		MyLocationListener.setRequestID(requestId);
		RadioButton rbClosedMode = (RadioButton) findViewById(R.id.rbClosedMode);
		RadioButton rbNormalMode = (RadioButton) findViewById(R.id.rbNormalMode);
		if (rbClosedMode.isChecked()) {
			String sendOption = SettingsUtil
					.getProfileName(getApplicationContext());
			if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_VIDEO)) {
				modeIntent.setClass(this, ClosedModeVideoCapture.class);
			} else if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_AUDIO)) {
				modeIntent.setClass(this, ClosedModeAudioRecorder.class);
			} else if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_PICTURE)) {
				modeIntent.setClass(this, ClosedModePictureCapture.class);
			}
		} else if (rbNormalMode.isChecked()) {
			String sendOption = SettingsUtil
					.getProfileName(getApplicationContext());
			if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_VIDEO)) {
				modeIntent.setClass(this, NormalModeVideoCapture.class);
			} else if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_AUDIO)) {
				modeIntent.setClass(this, NormalModeAudioRecorder.class);
			} else if (sendOption
					.equalsIgnoreCase(InstantHelperConstant.SETTING_PICTURE)) {
				modeIntent.setClass(this, NormalModePictureCapture.class);
			}

		}
		startActivity(modeIntent);
	}

	private String sendHelpRequestToCentrallApp() {
		String url = InstantHelperConstant.CentralAppURL
				+ "/androidhelprequest/newHelpRequest";
		Person person = selectUserById();
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("userNick", person
				.getUserNick()));
		postParameters.add(new BasicNameValuePair("userPassword", person
				.getUserPassword()));
		postParameters.add(new BasicNameValuePair("phoneId", androidId));
		String response = null;
		String result = "";
		try {
			response = CustomHttpClient.executeHttpPost(url, postParameters);
			String res = response.toString();
			JSONObject jObject = new JSONObject(res);
			result = jObject.getString("requestId");
		} catch (Exception e) {

		}
		return result;
	}

	public Person selectUserById() {
		myDbHelper = new DbHelper(main.this);
		SQLiteDatabase db = myDbHelper.getReadableDatabase();
		Cursor cursor = null;
		Person person = new Person();
		// Get the database and run the query
		String selection = InstantHelperConstant.DB_COLUMN_ID + "=1";
		try {
			cursor = db.query(InstantHelperConstant.DB_PERSON_TABLE, null,
					selection, null, null, null, null, null);
			Log.d(TAG, "in Cursor =" + cursor.toString());
			startManagingCursor(cursor);

		} catch (Exception e) {
			Log.d(TAG, "select query something wrong (IGNORE THIS)");
			// TODO: handle exception
		}
		while (cursor.moveToNext()) {
			person.setAddress(cursor.getString(2));
			person.seteMail(cursor.getString(3));
			person.setName(cursor.getString(4));
			person.setPhoneNumber(cursor.getString(5));
			person.setSurname(cursor.getString(6));
			person.setTCNo(cursor.getString(7));
			person.setUserNick(cursor.getString(8));
			person.setUserPassword(cursor.getString(9));
		}
		myDbHelper.close();
		db.close();
		cursor.close();
		return person;
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater contactMenu = getMenuInflater();
		contactMenu.inflate(R.menu.menu_button, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.contact:
			Intent contact = new Intent();
			contact.setClass(this, Contact.class);
			startActivity(contact);
			break;

		case R.id.settingsMenu:
			Intent settings = new Intent();
			settings.setClass(this, MyPreference.class);
			startActivity(settings);
			break;

		case R.id.synchronize:
			Intent synchronize = new Intent();
			synchronize.setClass(this, Synchronize.class);
			startActivity(synchronize);
			break;

		default:
			Intent aboutUsIntent = new Intent();
			aboutUsIntent.setClass(this, AboutUs.class);
			startActivity(aboutUsIntent);
			break;
		}
		return true;
	}

	private void helpButtonAvailable() {
		myDBHelper = new DbHelper(this);
		SQLiteDatabase db = myDBHelper.getReadableDatabase();
		Cursor cursor = null;
		// Get the database and run the query
		String selection = InstantHelperConstant.DB_COLUMN_ID + "=1";
		try {
			cursor = db.query(InstantHelperConstant.DB_PERSON_TABLE, null,
					selection, null, null, null, null, null);
			Log.d(TAG, "in Cursor =" + cursor.toString());
			startManagingCursor(cursor);

		} catch (Exception e) {
			Log.d(TAG, "select query something wrong (IGNORE THIS)");
			// TODO: handle exception
		}
		if (cursor.getCount() != 0) {
			isContactAdd = true;
		}

		myDBHelper.close();
		db.close();
		cursor.close();
		if (!isContactAdd) {
			buttonHelp.setEnabled(false);
		}else{
			buttonHelp.setEnabled(true);
		}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		super.onPostCreate(savedInstanceState);
		
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		super.onRestart();
		
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		super.onStart();
		
	}

	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		super.onUserLeaveHint();
		
	}

	@Override
	protected void onPostResume() {
		// TODO Auto-generated method stub
		super.onPostResume();
		helpButtonAvailable();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		gpsAvailableControl();
		super.onResume();
		
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		helpButtonAvailable();
		super.onBackPressed();
		
	}
}